import { observable, computed, flow, action, configure } from 'mobx';
import _ from 'lodash';

import {
  institutions,
  getPolicies,
  getPolicy,
  createPolicy,
  updatePolicy,
  removePolicy
} from '../services';
import members from './members';

/* function normalize(data, id, childrenKey, childId) {
  const res = { institutions: {}, productions: {} };
  _.forEach(data, d => {
    res.institutions[d[id]] = _.trim(d.name);
    if (d[childrenKey] && d[childrenKey].length > 0) {
      res.productions[d[id]] = {};
      _.forEach(d[childrenKey], dc => {
        res.productions[d[id]][dc[childId]] = _.trim(dc.name);
      });
    }
  });
  return res;
} */
function normalizeArr(data, id, childrenKey, childId) {
  const res = { institutions: [], productions: {} };
  _.forEach(data, d => {
    res.institutions.push({ value: d[id], label: d.name });
    if (d[childrenKey] && d[childrenKey].length > 0) {
      res.productions[d[id]] = [];
      _.forEach(d[childrenKey], dc => {
        res.productions[d[id]].push({
          value: dc[childId],
          label: _.trim(dc.name)
        })
      });
    }
  });
  return res;
}

configure({ enforceActions: true });
class Policies {
  @observable customerId = '';
  @observable baseData = {};
  @observable baseData_ins = [];
  @observable baseData_prod = {};
  @observable data = [];
  @observable current = null;
  @observable pending = false;
  @observable submitStatus = false;
  @computed
  get total() {
    return this.data.length;
  }
  init = flow(function*(customerId) {
    if ((customerId && customerId !== this.customerId) || this.total < 1) {
      yield this.fetch(customerId);
      this.customerId = customerId;
    }
    yield members.fetch(customerId);
  });

  initEdit = flow(function*(customerId, id) {
    if (!customerId) {
      throw new Error('没有目标客户id(customerId), 无法定位相关家庭成员');
    }
    yield members.fetch(customerId);
    yield this.fetchBaseData();
    this.customerId = customerId;
    if (id) {
      const target = yield getPolicy(customerId, id);
      if (target) {
        // _.forEach(target, (v, k) => {
        //   if (_.isNumber(v)) {
        //     target[k] = v.toString();
        //   }
        // });
        this.current = target;
      }
    }
  });
  fetch = flow(function*(id) {
    const data = yield getPolicies(id);
    if (data) {
      this.data = data.policies;
    }
  });
  fetchOne = flow(function*(customerId, id) {
    const data = yield getPolicy(customerId, id);
    if (data) {
      return data;
    }
  });
  fetchBaseData = flow(function*() {
    try {
      if (!_.isEmpty(this.baseData)) {
        return;
      }
      this.pending = true;
      const data = yield institutions();
      if (!_.isEmpty(data.insuranceCompanies)) {
        const _d = normalizeArr(
          data.insuranceCompanies,
          'insuranceCompanyId',
          'insuranceProducts',
          'insuranceProductId'
        );
        this.baseData_ins = _d.institutions;
        this.baseData_prod = _d.productions;
        this.baseData = _d;
      }
    } finally {
      this.pending = false;
    }
  });
  create = flow(function*({ customerId, ...values }) {
    this.pending = true;
    try {
      const data = yield createPolicy(customerId || this.customerId, values);
      if (data) {
        this.pending = false;
        this.submitStatus = false;
        yield this.fetch(this.customerId);
        return data;
      }
    } finally {
      this.pending = false;
      this.submitStatus = false;
    }
  });
  remove = flow(function*(id) {
    const data = yield removePolicy(this.customerId, id);
    if (data) {
      yield this.fetch(this.customerId);
    }
  });
  @action
  submit = stop => {
    if (stop) {
      this.submitStatus = false;
      return;
    }
    this.submitStatus = true;
  };
  update = flow(function*({ customerId, ...values }) {
    this.pending = true;
    try {
      const data = yield updatePolicy(customerId || this.customerId, {
        ...this.current,
        ...values
      });
      if (data) {
        this.pending = false;
        this.submitStatus = false;
        yield this.fetch(this.customerId);
        return data;
      }
    } finally {
      this.pending = false;
      this.submitStatus = false;
    }
  });
  @action
  reset = () => {
    this.current = null;
  };
}
export default new Policies();
